<?php

namespace App\Http\Controllers;

use App\Models\Red;
use App\Models\RedAccess;
use App\Models\RedRecord;
use App\Models\Setting;
use App\Models\SettingGain;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Kuyuan\Phpwidget\Str;

class RedController extends Controller
{
    // 红包数据
    private $Red = null;

    /**
     * 首页红包列表
     * @param Request $request
     * @return mixed
     */
    public function index(Request $request)
    {
        $_member_id = auth('member')->id();
        $_limit = $request->limit;
        $_enter_red = $request->input('enter_red',0);
        $_area = $request->input('area','');
        $Red = Red::select(
                'reds.id',
                'reds.member_id',
                'reds.media',
                'reds.red_type',
                'reds.area_type',
                'reds.area',
                'reds.number',
                'reds.numbered',
                'reds.title',
                'reds.start_time',
                'reds.end_time',
                'reds.question',
                'reds.answer',
                'reds.time_type',
                'reds.link',
                'reds.red_form',
                'reds.red_form_id'
            )
            ->where(function($query)use($_enter_red,$_area) {
                $query->where("status",2)
                    ->whereRaw("number > numbered")
                    ->when($_enter_red, function($query, $_enter_red) {
                        return $query->where('id','!=',$_enter_red);
                    })
                    ->where(function($query)use($_area) {
                        $query->orWhereRaw("`area_type` = 0 OR substring('{$_area}',1,CHAR_LENGTH(`area`)) = `area`");
                    });
            })
            ->orWhereRaw("(SELECT id FROM `".cool_table_name('red_records')."` WHERE pid = 0 AND red_id = ".cool_table_name('reds').".id AND member_id = {$_member_id} LIMIT 1)")
            ->offset($_limit[0])
            ->limit($_limit[1])
            ->orderByRaw("(SELECT id FROM `".cool_table_name('red_records')."` WHERE pid = 0 AND red_id = ".cool_table_name('reds').".id AND member_id = {$_member_id} LIMIT 1) ASC, id DESC");
        $Red = $Red->get();
        foreach($Red as $_k=>$_item) {
            $Red[$_k] = $_item->setAppends([
                'owner_nickname',
                'owner_header',
                'cover',
                'video',
                'images',
                'choice_question',
                'answer_question',
                'time',
                'owner',
                'under',
                'submit_form'
            ]);
        }
        return response(['data'=>$Red]);
    }

    /**
     * 前端首页获取一个红包详情
     * @param Request $request
     */
    public function show($_id)
    {
        $Red = Red::select(
                "id",
                "member_id",
                "red_type",
                "money",
                "pay",
                "charge",
                "pay_type",
                "type",
                "send_coupon",
                "coupon",
                "red_form",
                "red_form_id",
                "number",
                "numbered",
                "title",
                "media",
                "question",
                "answer",
                "award",
                "time_type",
                "start_time",
                "end_time",
                "area_type",
                "area",
                "link",
                "status"
            )
            ->where('id',$_id)
            ->first()
            ->setAppends([
                'owner_nickname',
                'owner_header',
                'cover',
                'video',
                'images',
                'choice_question',
                'answer_question',
                'time',
                'owner',
                'original_title',
                'under'
            ])->toArray();
        $Red['title'] = $Red['original_title'];
        $Red['pay'] = Str::format_money($Red['pay']);
        $Red['charge'] = Str::format_money($Red['charge']);
        $Red['money'] = Str::format_money($Red['money']);
        return response(['data'=>$Red]);
    }

    /**
     * 首页可开红包列表总数
     */
    public function homeListTotal(Request $request)
    {
        $_area = $request->input('area','');
        $_count = Red::where(function($query)use($_area) {
            $query->where("status",2)
                ->where("number",">","numbered")
                ->where(function($query)use($_area) {
                    $query->orWhereRaw("`area_type` = 0 OR substring('{$_area}',1,CHAR_LENGTH(`area`)) = `area`");
                });
        })->count();
        return response(['data'=>$_count]);
    }

    /**
     * 用户的红包列表
     */
    public function member(Request $request)
    {
        $_member_id = auth('member')->id();
        $_limit = $request->input('limit',[0,10]);
        $_enter_red_id = $request->input('enter_red_id',0);
        $Red = Red::where("member_id",$_member_id)
            ->where("status",">=",2)
            ->where("status","<",6)
            ->orderByRaw("id=".$_enter_red_id." DESC, number != numbered DESC, id DESC")
            ->offset($_limit[0])
            ->limit($_limit[1])
            ->get();
        if($Red) {
            foreach($Red as $item) {
                $item->setAppends([
                    'owner_nickname',
                    'owner_header',
                    'cover',
                    'video',
                    'images',
                    'choice_question',
                    'answer_question',
                    'time',
                    'owner',
                    'under'
                ]);
            }
        }
        return response(['data'=>$Red]);
    }

    /**
     * 修改红包
     * @param Request $request
     */
    public function edit($_id,Request $request)
    {
        $_red_data = $request->input();
        $_red_data['pay'] = Str::format_money($_red_data['pay'],true);
        $_red_data['money'] = Str::format_money($_red_data['money'],true);
        $_red_data['charge'] = Str::format_money($_red_data['charge'],true);
        $_red_data['answer'] = $this->setAnswer([
                'question' => $_red_data['question'],
                'choice_question' => $_red_data['choice_question'],
                'answer_question' => $_red_data['answer_question']
            ]);
        $_red_data['start_time'] = $this->setStartTime([
            'time' => $_red_data['time'],
            'time_type' => $_red_data['time_type']
        ]);
        $_red_data['end_time'] = $this->setEndTime([
            'time' => $_red_data['time'],
            'time_type' => $_red_data['time_type']
        ]);
        unset(
            $_red_data['choice_question'],
            $_red_data['answer_question'],
            $_red_data['time']
        );
        if(Red::where("id",$_id)->update($_red_data)) {
            return response(['data'=>'success']);
        } else {
            return response(['message'=>'修改失败'],402);
        }
    }

    /**
     * 修改设置答题红包
     * @param $_value
     * @return string
     */
    private function setAnswer($_value)
    {
        $_answer = "";
        if ($_value['question'] == 1) {
            $_answer = json_encode($_value['choice_question']);
        } else if ($_value['question'] == 2) {
            $_answer = json_encode($_value['answer_question']);
        }
        return $_answer;
    }

    /**
     * 设置红包开始时间
     * @param $_value
     * @return int
     */
    private function setStartTime($_value)
    {
        $_start_time = 0;
        if ($_value['time_type'] == 2) {
            $_start_time = $_value['time']["start"];
        }
        return $_start_time;
    }

    /**
     * 设置红包结束时间
     * @param $_value
     * @return int
     */
    private function setEndTime($_value)
    {
        $_end_time = 0;
        if ($_value['time_type'] == 2) {
            $_end_time = $_value['time']["end"];
        }
        return $_end_time;
    }

    /**
     * 停止发红包
     */
    public function stop($_id)
    {
        $Red = Red::find($_id);
        $Red->status = 4;
        if($Red->save()) {
            return response(['data'=>'success']);
        } else {
            return response(['message'=>'修改失败'],402);
        }
    }

    /**
     * 开始发红包
     * @param $_id
     * @return mixed
     */
    public function start($_id)
    {
        $Red = Red::find($_id);
        $Red->status = 2;
        if($Red->save()) {
            return response(['data'=>'success']);
        } else {
            return response(['message'=>'修改失败'],402);
        }
    }

    /**
     * 删除红包
     * @param $_id
     */
    public function destroy($_id)
    {
        DB::beginTransaction();
        try{
            $this->Red = Red::lockForUpdate()->find($_id);
            if(!$this->Red || ($this->Red->status != 2 && $this->Red->status != 4)) {
                throw new \PDOException('非法操作',402);
            }
            // 红包没有发完，退款给发包用户
            if($this->Red->numbered < $this->Red->number) {
                // 红包剩余金额
                $_surplus_money = $this->redBalance();
                if($this->Red->pay_type == 1) {
                    // 余额发红包，直接退回给用户余额
                    $this->balanceHandle($_surplus_money);
                } else {
                    // 微信支付，退款到微信支付钱包
                    $this->refund($_surplus_money,'red-refund',$this->Red->id,$this->Red->member_id);
                }
            }
            if(!Red::destroy($_id)) {
                throw new \PDOException('删除失败',402);
            }
            DB::commit();
            return response(['data'=>'success']);
        }catch (\PDOException $e) {
            DB::rollBack();
            return response(['message'=>$e->getMessage()],$e->getCode());
        }
    }

    /**
     * 获取红包剩余未发金额
     */
    private function redBalance()
    {
        if($this->Red->type == 1) {
            // 普通红包
            $_surplus_number = $this->Red->number - $this->Red->numbered;
            $_balance = $_surplus_number * $this->Red->money;
        } else {
            // 手气红包
            $_already_money = RedRecord::where("red_id", $this->Red->id)
                ->sum("money");
            $_balance = $this->Red->money - $_already_money;
        }
        return $_balance;
    }

    /**
     * 红包手续费比例
     */
    public function gain()
    {
        return response(['data'=>SettingGain::first()]);
    }

    /**
     *验证当前用户是否有权限发红包
     */
    public function checkAccess()
    {
        $Setting = Setting::first();
        if($Setting->open_send) {
            $_response = response(["data"=>1]);
        } else {
            if(RedAccess::where("member_id",auth("member")->id())
                    ->exists()){
                $_response = response(["data"=>1]);
            } else {
                $_response = response(["data"=>0]);
            }
        }
        return $_response;
    }

    //---------------------------------------------

    /**
     * 获取红包列表
     */
    public function getList(Request $request)
    {
        $_limit = $request->input('limit', [0,10]);
        $Red = Red::where("status","!=",1)
            ->where("status","!=",6)
            ->where("status","!=",8)
            ->orderBy("id","desc")
            ->offset($_limit[0])
            ->limit($_limit[1])
            ->get();
        if($Red) {
            foreach($Red as $item) {
                $item->setAppends([
                    "owner_header",
                    "owner_nickname",
                    "original_title"
                ]);
                $item->money = Str::format_money($item->money);
            }
        }
        return response(["data"=>$Red]);
    }

    /**
     * 红包总数
     */
    public function total()
    {
        return response([
            "data" => Red::where("status","!=",1)
                ->where("status","!=",6)
                ->where("status","!=",8)
                ->count()
        ]);
    }
}
